package vip.ola.pay.batchpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransOrderQueryModel;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.constant.PayConstant;
import vip.ola.core.common.util.MD5Util;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.TransOrder;
import vip.ola.pay.channel.BaseTrans;
import vip.ola.pay.channel.alipay.AlipayConfig;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: dingzhiwei
 * @date: 17/12/25
 * @description:
 */
@Service
public class TestBatchPay  {

    private static final MyLog _log = MyLog.getLog(TestBatchPay.class);



    public static JSONObject trans() {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String downSn = "DS" + df.format(System.currentTimeMillis());
            TreeMap<String, String> obj = new TreeMap<String, String>();
            obj.put("bankcardAccountName", "张三");
            obj.put("version", "1.0.1");
            obj.put("bankcardAccountNo", "62258878542702222");
            obj.put("amount", "1");
            obj.put("merchantId", PaysUtil.memberCode);
            obj.put("bankCode", "工商银行");
            obj.put("notifyUrl", "http://150.109.63.144:3503/api/trans/notify");
            obj.put("merchantOrderNo", downSn);
            obj.put("model", "800");
            // 生成签名
            StringBuffer paramstr = new StringBuffer();
            for (String pkey : obj.keySet()) {
                String pvalue = obj.get(pkey);
                if (pvalue != null && pvalue != "") {
                    paramstr.append(pkey + "=" + pvalue + "&");
                }
            }
            String paramsrc = paramstr.substring(0, paramstr.length() - 1);
            System.out.println(paramsrc);
//            String sign = sign(paramsrc);
//            byte[] queryBytes;
            String queryBytes = RSAUtils.sign(paramsrc, PaysUtil.privateKey);
//            String cipherData = Base64Utils.encode(queryBytes);
            System.out.println(queryBytes);
            obj.put("sign", queryBytes);
            _log.info("查询请求url={}，param={}",PaysUtil.url,obj);
            String respData = call("https://gateway.hhspay.com/api/remitOrder/create",obj);
            System.out.println(respData);
//            _log.info("query end ,the respData->{}",respData);
//            JSONObject jsonObject = JSONObject.parseObject(respData);
//            if (jsonObject != null) {
//                String code = jsonObject.getString("code");
//                if ("1".equals(code)) {
//                    JSONObject dataObject = JSONObject.parseObject(jsonObject.getString("data"));
//                    String orderId=dataObject.getString("orderId");
//
//                }
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    public static String call(String url, Map param) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        // 响应模型
        CloseableHttpResponse response = null;
        String responseContext = null;
        try {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(param), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                responseContext = EntityUtils.toString(responseEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContext;
    }

    private static String sign(String paramSrc) {
        StringBuffer strbuff = new StringBuffer();
        strbuff.append(paramSrc + "&key=" + PaysUtil.memberSecret);
        String sign = null;
        try {
            System.out.println("****待签名信息:"+strbuff.toString());
            sign = Md5Util.MD5Encode(strbuff.toString(), "UTF-8").toUpperCase();
            System.out.println("签名:" + sign);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sign;
    }

    public static JSONObject query() {
        try {
            String downSn ="yous20210604211305";
            TreeMap<String, String> obj = new TreeMap<String, String>();
            obj.put("merchant_sn", PaysUtil.memberCode);
            obj.put("down_sn", downSn);
            // 生成签名
            StringBuffer paramstr = new StringBuffer();
            for (String pkey : obj.keySet()) {
                String pvalue = obj.get(pkey);
                if (pvalue != null && pvalue != "") {
                    paramstr.append(pkey + "=" + pvalue + "&");
                }
            }
            String paramsrc = paramstr.substring(0, paramstr.length() - 1);
            String sign = sign(paramsrc);
            _log.info("batch pay the request is->{}",sign);
            String str = HttpClientUtil.submitPost(PaysUtil.url + "/api/settle/query",
                    "merchant_sn=" + PaysUtil.memberCode + "&down_sn=" + downSn+ "&sign=" + sign, "utf-8", 60000, 60000);
            _log.info("batch pay the res is->{}",str);
            JSONObject jsonObject = JSONObject.parseObject(str);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    public static JSONObject balance(String payParam) {
        try {
            JSONObject accountParams = JSONObject.parseObject(payParam);
            String mchId = "22000254";
            String privateKey = "XRX8JNQ7U6BI3DVLT25AFWBZ00LJAE9W7PGKXCCJALBOPMJL8FPBGQWRMBJUFLJFUCPPSJJVBPM4N4HFSYX7EDN6P5Z2OHVPIIYSEKF1LJIHCQSXZ8FGMWR0Y6EGSDDX";
            String balanceUrl = "http://api.shengqian.icu/api/agentpay/query_balance";
            TreeMap<String, String> obj = new TreeMap<String, String>();
            SimpleDateFormat fm = new SimpleDateFormat("yyyyMMddHHmmss");
            String reqTime =fm.format(new Date());
            obj.put("reqTime", reqTime);
            obj.put("mchId",mchId);
            // 生成签名
            String querySign = PayDigestUtil.getSign(obj, privateKey);  //签名
            obj.put("sign", querySign);
            _log.info("FeifandfTransService余额查询请求={}",obj);
            NameValuePair pair = new BasicNameValuePair("mchId", mchId);
            NameValuePair pair4 = new BasicNameValuePair("sign", querySign);
            NameValuePair pair11 = new BasicNameValuePair("reqTime", reqTime);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(16);
            nameValuePairs.add(pair);
            nameValuePairs.add(pair4);
            nameValuePairs.add(pair11);
            String respData = postWithParamsForString(balanceUrl,nameValuePairs);
            _log.info("余额查询结束respData->{}",respData);
            if (StringUtils.isNotEmpty(respData)){
                JSONObject jsonObject = JSONObject.parseObject(respData);
                if (jsonObject != null){
                    String code = jsonObject.getString("retCode");
                    if ("SUCCESS".equals(code)  ){
                        Integer totalAmt = jsonObject.getInteger("availableAgentpayBalance");
                        BigDecimal amount = new BigDecimal(totalAmt).divide(new BigDecimal(100)).setScale(2);
                        JSONObject result = new JSONObject();
                        result.put("retCode","SUCCESS");
                        result.put("cashBalance",amount);
                        return result;
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String postWithParamsForString(String url, List<NameValuePair> params){
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost =   new HttpPost(url);
        String s = "";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            HttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                HttpEntity entity = response.getEntity();
                s = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }



    public static void main (String args[]){
//        trans();

        balance(null);
//        query();
    //    System.out.println(MD5Util.string2MD5("123456"));
//        String url ="http://payapi.gb666.net/Notify/GetNotify?income=8950&payOrderId=DS12021102414294428299&amount=10000&mchId=9326&productId=10001&paySuccTime=1635057091000&sign=80A0863AB2FC09EA60F1556212EE46F3&channelOrderNo=&backType=2&param1=&param2=&outTradeNo=2021103222321958021&status=2";
//      String resp=  PayUtil.call4Post(url);
//        System.out.println(resp);
        String money = "2.000000";
        System.out.println(BigDecimal.valueOf(Double.valueOf(money)).longValue());
    }


}
